#!/usr/bin/env python

from random import Random
import os,commands,pprint,time
from AutoSsh import *
from cm_api.api_client import ApiResource
class InStall:
    def __init__(self,cm_host,Clustername,Servicetype,Ip):
        self.ip = Ip
        self.user = 'root'
        self.port=22
        self.cm_host = cm_host
        self.clustername = Clustername
        self.servicetype=Servicetype
        self.servicename = 'DATANODE'
        self.pkey='/root/.ssh/id_rsa.pub'
        self.yuminstall='/usr/bin/yum clean all;/usr/bin/yum -y install psmisc cyrus-sasl-gssapi ntp fuse portmap fuse-libs mod_ssl python-psycopg2 MySQL-python lsb'
        self.ntpconf='scp -r /etc/ntp.conf %s:/etc/' % (self.ip)
        self.ntpd='systemctl enable ntpd.service;/usr/bin/systemctl start ntpd.service;sleep 0.4 ; /usr/sbin/ntpdc -c loopinfo'
        self.cmsrcdir='/usr/local/src'
        self.cmagt='%s/CDH/cloudera-manager-agent-5.5.2-1.cm552.p0.16.el7.x86_64.rpm' %(self.cmsrcdir)
        self.cmdmn='%s/CDH/cloudera-manager-daemons-5.5.2-1.cm552.p0.16.el7.x86_64.rpm' %(self.cmsrcdir)
        self.scpcmagt='scp -r %s %s:%s/' % (self.cmagt,self.ip,self.cmsrcdir)
        self.scpcmdmn='scp -r %s %s:%s/' % (self.cmdmn,self.ip,self.cmsrcdir)
        self.inscmagt='/usr/bin/rpm -ivh %s/cloudera-manager-agent-5.5.2-1.cm552.p0.16.el7.x86_64.rpm' % (self.cmsrcdir)
        self.inscmdmn='/usr/bin/rpm -ivh %s/cloudera-manager-daemons-5.5.2-1.cm552.p0.16.el7.x86_64.rpm' % (self.cmsrcdir)
        self.cmagconf='scp -r /etc/cloudera-scm-agent/config.ini %s:/etc/cloudera-scm-agent/' % (self.ip)
        self.startcmagt='/etc/init.d/cloudera-scm-agent restart'
        self.hostname='hostname'
        self.now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.api = ApiResource(self.cm_host, username="admin", password="admin",version=11)
        self.cluster = self.api.get_cluster(self.clustername)
        self.hdfs = self.cluster.get_service(self.servicetype) 

    def log(self,Message):
        Logdir = './logs'
        Logfile = Logdir + '/'+ 'install.log'
        if os.path.exists(Logdir):
            pass
        else:
            os.makedirs(Logdir)
        Message = str(Message)
        with open(Logfile, 'a+') as logs:
            logs.write(Message)
        
    def cmagentinstall(self):
        status = 0
        result = None
        for i in range(3):
            try:
                now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                print "ip:%s\nyuminstall:%s\nntpconf:%s\nntpd:%s\ncmsrcdir:%s\ncmagt:%s\ncmdmn:%s\nscpcmagt:%s\nscpcmdmn:%s\ninscmagt:%s\ninscmdmn:%s\ncmagconf:%s\nstartcmagt:%s\n" %(self.ip,self.yuminstall,self.ntpconf,self.ntpd,self.cmsrcdir,self.cmagt,self.cmdmn,self.scpcmagt,self.scpcmdmn,self.inscmagt,self.inscmdmn,self.cmagconf,self.startcmagt)
                AutoSsh().executekey(self.ip,self.user,self.yuminstall,self.pkey)
                commands.getoutput(self.ntpconf)
                AutoSsh().executekey(self.ip,self.user,self.ntpd,self.pkey)
                commands.getoutput(self.scpcmagt)
                commands.getoutput(self.scpcmdmn)
                AutoSsh().executekey(self.ip,self.user,self.inscmdmn,self.pkey)
                AutoSsh().executekey(self.ip,self.user,self.inscmagt,self.pkey)
                commands.getoutput(self.cmagconf)
                AutoSsh().executekey(self.ip,self.user,self.startcmagt,self.pkey)
                info="%s\t%s cloudera manager agent was installed Completed !\n" % (now,self.ip)
                status = 1
            except:
                time.sleep(3)
            return result
        self.log(info)

    def addcluster(self):
        dnlist = []
        self.cmagentinstall()
        print "Install clouderamanager agent is Completed !"
        hostname = AutoSsh().executekey(self.ip,self.user,self.hostname,self.pkey).strip()
        node = self.api.get_host(hostname) 
        strhost = ''.join(''.join(hostname.split('-')).split('.'))
        role_name='%s%s%s' % (self.servicetype,self.servicename,strhost)
        self.cluster.add_hosts([node.hostId])
        self.hdfs.create_role(role_name,self.servicename,node.hostId)
        print "Install %s had Completed!" % (self.servicename)
        dnlist.append(self.ip)
        dnlist.append(str(node.hostId))
        dnlist.append(role_name)
        return dnlist
    def group(self,nodelist):
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        hostname = AutoSsh().executekey(nodelist[0],self.user,self.hostname,self.pkey).strip()
        node = self.api.get_host(hostname) 
        groups = ['data11','data12','data13','data14','DatanodeDefault']
        check_disk="grep hdfs /etc/fstab | awk '{print $2}' |awk -F '/' '{print $2}'| tail -1"
        lastdisk = (AutoSsh().executekey(nodelist[0],self.user,check_disk,self.pkey)).strip()
        host_template = ''
        cn = 0
        if len(lastdisk) == 0 or 'data' not in lastdisk :
            host_template = 'DatanodeDefault'
        else:
            host_template = lastdisk
            cn = 1
        tolog = "%s\t%s -> %s -> %s -> %s -> %s !\n" % (now,nodelist[0],self.clustername,self.servicename,host_template,nodelist[2])
        print tolog
        new_template = self.cluster.get_host_template(host_template)
        new_template.apply_host_template([node.hostId],nodelist[2])
        if cn == 1:
            self.hdfs.start_roles(nodelist[2])
            #print "%s start datanode group : %s "  % (nodelist[0],host_template)
        self.log(tolog)

    def print_for(self):
        for i in range(10):
            print i
        time.sleep(3)
